package com.xinyu.controller;

import com.xinyu.domain.DailyAttachment;
import com.xinyu.domain.User;
import com.xinyu.service.IDailyAttachmentService;
import com.xinyu.service.IUserService;
import com.xinyu.utils.JWTUtils;
import com.xinyu.vo.BaseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@RequestMapping("/feedback/file")
public class FeedbackAttachmentController {

    @Autowired
    private IDailyAttachmentService dailyAttachmentService;

    @Autowired
    private IUserService userService;

    @Autowired
    private HttpServletRequest request;

    @DeleteMapping("/{id}")
    public ResponseEntity<BaseResult> delete(@PathVariable Integer id) {
        DailyAttachment attachment = dailyAttachmentService.getById(id);
        if (attachment == null) {
            return ResponseEntity.ok(BaseResult.error("附件不存在"));
        }
        Integer operatorId = JWTUtils.getUserIdFromToken(request.getHeader("Authorization"));
        if (operatorId == null) {
            return ResponseEntity.ok(BaseResult.error("未登录"));
        }
        boolean canDelete = Objects.equals(operatorId, attachment.getCreatedBy());
        if (!canDelete) {
            User operator = userService.getById(operatorId);
            canDelete = operator != null && operator.getIsAdmin() != null && operator.getIsAdmin() == 1;
        }
        if (!canDelete) {
            return ResponseEntity.ok(BaseResult.error("无权限删除附件"));
        }
        dailyAttachmentService.removeById(id);
        return ResponseEntity.ok(BaseResult.ok());
    }
}
